var _ = require('lodash')

function timePeriod (date) {
  let hour = date.getHours()
  let moring = '5,6,7,8'.split(',')
  let forenoon = '8,9,10,11'.split(',')
  let midday = '12,13'.split(',')
  let afternoon = '14,15,16'.split(',')
  let dusk = '17,18,19'.split(',')
  let evening = '20,21,22,23,24,1,2,3,4,5'.split(',')
  let say = {
    '早上好': moring,
    '上午好': forenoon,
    '中午好': midday,
    '下午好': afternoon,
    '傍晚好': dusk,
    '晚上好': evening
  }
  for (let key of Object.keys(say)) {
    if (_.indexOf(say[key], hour.toString()) !== -1) {
      return key
    }
  }
}

function formatDate (date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  // 遍历这个对象
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      // console.log(`${k}`)
      let str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

function padLeftZero (str) {
  return ('00' + str).substr(str.length)
}

export {
  timePeriod,
  formatDate
}
